<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-loading size="24px" vertical v-if="isLoading">加载中...</van-loading>
      <div class="goods">
        <GoodsItem
          id="goodslist"
          v-for="(item, index) in historyData"
          :key="index"
          :url="item.img_url"
          :describe="item.title"
          :price="item.market_price"
          :buy="item.buy"
          @click="particulars(item.id)"
        ></GoodsItem>
      </div>
    </van-pull-refresh>

    <van-divider v-if="isLoadDone">已经全部加载</van-divider>
  </div>
</template>

<script setup>
import { getHistory } from "@/api";
import _ from "lodash";
import GoodsItem from "@/components/GoodsItem.vue";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
const $router = useRouter();
const page = ref(1);
const pagesize = ref(8);
const historyData = ref([]);
const isLoadDone = ref(false);
const isLoading = ref(false);

const particulars = (id) => {
  $router.push("/particulars/" + id);
};

const onRefresh = async () => {
  isLoading.value = true;
  page.value = 1;
  historyData.value = [];
  let data = await getHistory({ page: page.value, pagesize: pagesize.value });
  if (data.length > 0) {
    isLoading.value = false;
    historyData.value = data;
  }
};

const loadGoodsList = async () => {
  // 加载完成就不再触发滚动事件，不再触发请求
  if (isLoadDone.value) {
    return;
  }
  //滚上去的高度
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  //   网页视口的宽度
  let windowHeight =
    document.documentElement.clientHeight || document.body.clientHeight;
  //整个页面的高度
  let pageHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight;

  if (Math.ceil(scrollTop) + windowHeight === pageHeight) {
    page.value++;
    let data = await getHistory({
      page: page.value,
      pagesize: pagesize.value,
    });
    // this.isLoadDone = false;
    if (data.length === 0) {
      // 说明数据加载完毕了
      isLoadDone.value = true;
      return;
    }
    historyData.value = [...historyData.value, ...data];
  }
};

const throttleLoadGoodsList = _.throttle(loadGoodsList, 300);

onMounted(async () => {
  let data = await getHistory({ page: page.value, pagesize: pagesize.value });
  historyData.value = data;
  // 给窗口绑定滚动事件
  window.addEventListener("scroll", throttleLoadGoodsList);
});

onBeforeUnmount(() => {
  window.removeEventListener("scroll", throttleLoadGoodsList);
});
</script>

<style lang="scss" scoped>
.goods {
  display: flex;
  flex-wrap: wrap;
  // justify-content: center;
  padding: 5px;

  #goodslist {
    margin: 5px;
  }
}
</style>
